package com.alawn.web.anon;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.ocpsoft.rewrite.annotation.Join;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

import com.alawn.framework.core.component.CaptchaService;
import com.alawn.framework.core.exception.MessageResolvableException;
import com.alawn.framework.core.web.faces.annotation.MessageRequired;
import com.alawn.framework.core.web.faces.controller.FacesController;
import com.alawn.framework.services.system.Preference;
import com.alawn.security.exception.CaptchaErrorException;

@Controller("/login.faces")
@Join(path = "/login", to = "/login.faces")
public class LoginController extends FacesController {

	@Value("${myzone.faces.web.loginTimes}")
	private String loginTimes;

	@Autowired
	private CaptchaService captchaService;

	@Override
	public void initPage() {
		putSessionScope("guestPreferences", new Preference());
		if (isLogin()) {
			redirectInternal("/index");
		}
		refreshCaptcha();
	}

	public void refreshCaptcha() {
		putViewScope("captchaImg", captchaService.createCaptcha(getRequest()));
	}

	@MessageRequired(growl = false)
	public void onLogin() {
		if (!isLogin()) {
			String exception = (String) getRequest().getAttribute("shiroLoginFailure");
			MessageResolvableException e = null;
			if (StringUtils.isNotBlank(exception)) {
				if (UnknownAccountException.class.getName().equals(exception)) {
					e = new MessageResolvableException("security", "usernameError", new String[0]);
				} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
					e = new MessageResolvableException("security", "usernameOrPasswordError", new String[0]);
				} else if (LockedAccountException.class.getName().equals(exception)) {
					e = new MessageResolvableException("security", "lockedAccountError", new String[0]);
				} else if (ExcessiveAttemptsException.class.getName().equals(exception)) {
					e = new MessageResolvableException("security", "excessiveAttempts", new String[] { loginTimes });
				} else if (CaptchaErrorException.class.getName().equals(exception)) {
					e = new MessageResolvableException("security", "captchaError", new String[0]);
				} else {
					e = new MessageResolvableException("security", "contactTheAdministrator", new String[0]);
				}
				if (e != null) {
					refreshCaptcha();
					throw e;
				}
			}
		}
	}

	private boolean isLogin() {
		return SecurityUtils.getSubject().isAuthenticated();
	}

}
